/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.daydream.template.sequence;

import com.google.common.base.MoreObjects;

import org.pajamas.daydream.template.sequence.segment.SegmentDefinitionParser;
import org.pajamas.daydream.template.sequence.segment.SegmentTokenSplitter;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author william
 * @since 2024/4/3
 */
public class SequenceTemplate {
    public static final SequenceTemplate CONTEXT_LESS = new SequenceTemplate();
    private final SegmentDefinitionParser parser;
    private final List<SequenceContext> contexts;

    public SequenceTemplate(@Nullable SegmentDefinitionParser parser, @Nullable SequenceContext... contexts) {
        this.parser = MoreObjects.firstNonNull(parser, new SegmentTokenSplitter());
        this.contexts = Arrays.stream(MoreObjects.firstNonNull(contexts, new SequenceContext[0]))
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

    }

    public SequenceTemplate(@Nullable SequenceContext... contexts) {
        this(null, contexts);
    }

    @Nonnull
    public Sequence create(@Nonnull String pattern) {
        return new Sequence(this.parser, this.contexts, Objects.requireNonNull(pattern));
    }
}
